<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>代码转UTF-16编码工具</title>
  <style>
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      margin: 0;
      padding: 20px;
      min-height: 100vh;
    }

    .container {
      max-width: 1200px;
      margin: 0 auto;
      background: white;
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
      overflow: hidden;
    }

    .header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 30px;
      text-align: center;
    }

    .header h1 {
      margin: 0;
      font-size: 2.5em;
      font-weight: 300;
    }

    .header p {
      margin: 10px 0 0 0;
      opacity: 0.9;
      font-size: 1.1em;
    }

    .content {
      padding: 30px;
    }

    .input-section,
    .output-section {
      margin-bottom: 30px;
    }

    .section-title {
      font-size: 1.3em;
      font-weight: 600;
      color: #333;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 2px solid #667eea;
    }

    .input-group {
      margin-bottom: 20px;
    }

    label {
      display: block;
      margin-bottom: 8px;
      font-weight: 600;
      color: #555;
    }

    textarea {
      width: 100%;
      min-height: 200px;
      padding: 15px;
      border: 2px solid #e1e5e9;
      border-radius: 8px;
      font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
      font-size: 14px;
      line-height: 1.5;
      resize: vertical;
      transition: border-color 0.3s ease;
    }

    textarea:focus {
      outline: none;
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    .controls {
      display: flex;
      gap: 15px;
      flex-wrap: wrap;
      margin-bottom: 20px;
    }

    button {
      padding: 12px 24px;
      border: none;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .btn-primary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }

    .btn-primary:hover {
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
    }

    .btn-secondary {
      background: #f8f9fa;
      color: #495057;
      border: 2px solid #e9ecef;
    }

    .btn-secondary:hover {
      background: #e9ecef;
      border-color: #dee2e6;
    }

    .btn-danger {
      background: #dc3545;
      color: white;
    }

    .btn-danger:hover {
      background: #c82333;
    }

    .output-container {
      background: #f8f9fa;
      border: 2px solid #e9ecef;
      border-radius: 8px;
      padding: 20px;
      min-height: 100px;
    }

    .output-text {
      font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
      font-size: 14px;
      line-height: 1.6;
      white-space: pre-wrap;
      word-break: break-all;
      color: #333;
    }

    .format-options {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 15px;
      margin-bottom: 20px;
    }

    .option-group {
      background: #f8f9fa;
      padding: 15px;
      border-radius: 8px;
      border: 1px solid #e9ecef;
    }

    .option-group label {
      font-size: 0.9em;
      margin-bottom: 5px;
    }

    select,
    input[type="checkbox"] {
      width: 100%;
      padding: 8px;
      border: 1px solid #ced4da;
      border-radius: 4px;
      font-size: 14px;
    }

    .stats {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
      gap: 15px;
      margin-top: 20px;
    }

    .stat-item {
      background: #e3f2fd;
      padding: 15px;
      border-radius: 8px;
      text-align: center;
      border-left: 4px solid #2196f3;
    }

    .stat-value {
      font-size: 1.5em;
      font-weight: bold;
      color: #1976d2;
    }

    .stat-label {
      font-size: 0.9em;
      color: #666;
      margin-top: 5px;
    }

    .copy-btn {
      position: relative;
    }

    .copy-btn::after {
      content: "复制";
      position: absolute;
      top: -30px;
      left: 50%;
      transform: translateX(-50%);
      background: #333;
      color: white;
      padding: 5px 10px;
      border-radius: 4px;
      font-size: 12px;
      opacity: 0;
      transition: opacity 0.3s ease;
      pointer-events: none;
    }

    .copy-btn:hover::after {
      opacity: 1;
    }

    @media (max-width: 768px) {
      .controls {
        flex-direction: column;
      }

      .format-options {
        grid-template-columns: 1fr;
      }

      .stats {
        grid-template-columns: repeat(2, 1fr);
      }
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="header">
      <h1>🔤 代码转UTF-16编码工具</h1>
      <p>将代码文本转换为UTF-16编码格式，支持多种输出格式</p>
    </div>

    <div class="content">
      <div class="input-section">
        <div class="section-title">📝 输入代码</div>
        <div class="input-group">
          <label for="inputCode">请输入要转换的代码：</label>
          <textarea id="inputCode"
            placeholder="在此输入您的代码...&#10;&#10;示例：&#10;function hello() {&#10;    console.log('Hello, World!');&#10;    return 'Hello';&#10;}&#10;&#10;const message = '你好，世界！';&#10;console.log(message);"></textarea>
        </div>

        <div class="format-options">
          <div class="option-group">
            <label for="outputFormat">输出格式：</label>
            <select id="outputFormat">
              <option value="hex">十六进制 (0x00)</option>
              <option value="unicode">Unicode转义 (\u0000)</option>
              <option value="decimal">十进制数组</option>
              <option value="binary">二进制</option>
              <option value="arraybuffer">ArrayBuffer</option>
            </select>
          </div>

          <div class="option-group">
            <label for="encoding">编码方式：</label>
            <select id="encoding">
              <option value="utf16le">UTF-16 LE (小端序)</option>
              <option value="utf16be">UTF-16 BE (大端序)</option>
            </select>
          </div>

          <div class="option-group">
            <label>
              <input type="checkbox" id="includeBOM" checked>
              包含BOM (字节顺序标记)
            </label>
          </div>

          <div class="option-group">
            <label>
              <input type="checkbox" id="formatOutput" checked>
              格式化输出
            </label>
          </div>
        </div>

        <div class="controls">
          <button class="btn-primary" onclick="convertToUTF16()">
            🔄 转换为UTF-16
          </button>
          <button class="btn-secondary" onclick="clearInput()">
            🗑️ 清空输入
          </button>
          <button class="btn-secondary" onclick="loadExample()">
            📋 加载示例
          </button>
        </div>
      </div>

      <div class="output-section">
        <div class="section-title">📤 转换结果</div>
        <div class="output-container">
          <div class="output-text" id="outputResult">等待转换...</div>
        </div>

        <div class="controls">
          <button class="btn-primary copy-btn" onclick="copyToClipboard()">
            📋 复制结果
          </button>
          <button class="btn-secondary" onclick="downloadResult()">
            💾 下载文件
          </button>
          <button class="btn-danger" onclick="clearOutput()">
            🗑️ 清空结果
          </button>
        </div>

        <div class="stats" id="stats">
          <div class="stat-item">
            <div class="stat-value" id="charCount">0</div>
            <div class="stat-label">字符数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value" id="byteCount">0</div>
            <div class="stat-label">字节数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value" id="lineCount">0</div>
            <div class="stat-label">行数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value" id="encodingSize">0</div>
            <div class="stat-label">编码后大小</div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
    function convertToUTF16() {
      const input = document.getElementById('inputCode').value;
      const outputFormat = document.getElementById('outputFormat').value;
      const encoding = document.getElementById('encoding').value;
      const includeBOM = document.getElementById('includeBOM').checked;
      const formatOutput = document.getElementById('formatOutput').checked;

      if (!input.trim()) {
        document.getElementById('outputResult').textContent = '请输入要转换的代码！';
        return;
      }

      try {
        let result = '';
        const encoder = new TextEncoder();
        const decoder = new TextDecoder();

        // 创建UTF-16编码的ArrayBuffer
        const utf16Buffer = new ArrayBuffer(input.length * 2 + (includeBOM ? 2 : 0));
        const view = new DataView(utf16Buffer);
        let offset = 0;

        // 添加BOM
        if (includeBOM) {
          if (encoding === 'utf16le') {
            view.setUint16(0, 0xFFFE, false); // LE BOM
          } else {
            view.setUint16(0, 0xFEFF, false); // BE BOM
          }
          offset = 2;
        }

        // 编码字符
        for (let i = 0; i < input.length; i++) {
          const charCode = input.charCodeAt(i);
          if (encoding === 'utf16le') {
            view.setUint16(offset, charCode, true);
          } else {
            view.setUint16(offset, charCode, false);
          }
          offset += 2;
        }

        // 根据输出格式生成结果
        switch (outputFormat) {
          case 'hex':
            result = arrayBufferToHex(utf16Buffer, formatOutput);
            break;
          case 'unicode':
            result = arrayBufferToUnicode(utf16Buffer, includeBOM, formatOutput);
            break;
          case 'decimal':
            result = arrayBufferToDecimal(utf16Buffer, formatOutput);
            break;
          case 'binary':
            result = arrayBufferToBinary(utf16Buffer, formatOutput);
            break;
          case 'arraybuffer':
            result = arrayBufferToString(utf16Buffer, formatOutput);
            break;
        }

        document.getElementById('outputResult').textContent = result;
        updateStats(input, utf16Buffer.byteLength);

      } catch (error) {
        document.getElementById('outputResult').textContent = `转换错误: ${error.message}`;
      }
    }

    function arrayBufferToHex(buffer, format) {
      const uint8Array = new Uint8Array(buffer);
      let hex = '';

      for (let i = 0; i < uint8Array.length; i++) {
        hex += uint8Array[i].toString(16).padStart(2, '0').toUpperCase();
        if (format && (i + 1) % 16 === 0) hex += '\n';
        else if (format && (i + 1) % 2 === 0) hex += ' ';
      }

      return hex;
    }

    function arrayBufferToUnicode(buffer, includeBOM, format) {
      const uint8Array = new Uint8Array(buffer);
      let unicode = '';
      let startIndex = includeBOM ? 2 : 0;

      for (let i = startIndex; i < uint8Array.length; i += 2) {
        const charCode = (uint8Array[i] << 8) | uint8Array[i + 1];
        unicode += `\\u${charCode.toString(16).padStart(4, '0').toUpperCase()}`;
        if (format && (i + 2) % 32 === 0) unicode += '\n';
      }

      return unicode;
    }

    function arrayBufferToDecimal(buffer, format) {
      const uint8Array = new Uint8Array(buffer);
      let decimal = '';

      for (let i = 0; i < uint8Array.length; i++) {
        decimal += uint8Array[i];
        if (i < uint8Array.length - 1) decimal += ', ';
        if (format && (i + 1) % 16 === 0) decimal += '\n';
      }

      return decimal;
    }

    function arrayBufferToBinary(buffer, format) {
      const uint8Array = new Uint8Array(buffer);
      let binary = '';

      for (let i = 0; i < uint8Array.length; i++) {
        binary += uint8Array[i].toString(2).padStart(8, '0');
        if (i < uint8Array.length - 1) binary += ' ';
        if (format && (i + 1) % 8 === 0) binary += '\n';
      }

      return binary;
    }

    function arrayBufferToString(buffer, format) {
      const uint8Array = new Uint8Array(buffer);
      let result = 'new Uint8Array([';

      for (let i = 0; i < uint8Array.length; i++) {
        result += uint8Array[i];
        if (i < uint8Array.length - 1) result += ', ';
        if (format && (i + 1) % 16 === 0) result += '\n  ';
      }

      result += ']);';
      return result;
    }

    function updateStats(input, byteLength) {
      document.getElementById('charCount').textContent = input.length;
      document.getElementById('byteCount').textContent = byteLength;
      document.getElementById('lineCount').textContent = input.split('\n').length;
      document.getElementById('encodingSize').textContent = (byteLength / 1024).toFixed(2) + ' KB';
    }

    function copyToClipboard() {
      const output = document.getElementById('outputResult').textContent;
      if (output && output !== '等待转换...' && !output.startsWith('转换错误')) {
        navigator.clipboard.writeText(output).then(() => {
          const btn = event.target;
          const originalText = btn.innerHTML;
          btn.innerHTML = '✅ 已复制';
          setTimeout(() => {
            btn.innerHTML = originalText;
          }, 2000);
        }).catch(err => {
          console.error('复制失败:', err);
          alert('复制失败，请手动复制');
        });
      }
    }

    function downloadResult() {
      const output = document.getElementById('outputResult').textContent;
      if (output && output !== '等待转换...' && !output.startsWith('转换错误')) {
        const blob = new Blob([output], { type: 'text/plain;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `utf16-encoded-${Date.now()}.txt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }
    }

    function clearInput() {
      document.getElementById('inputCode').value = '';
    }

    function clearOutput() {
      document.getElementById('outputResult').textContent = '等待转换...';
      document.getElementById('charCount').textContent = '0';
      document.getElementById('byteCount').textContent = '0';
      document.getElementById('lineCount').textContent = '0';
      document.getElementById('encodingSize').textContent = '0';
    }

    function loadExample() {
      const example = `function hello() {
    console.log('Hello, World!');
    return 'Hello';
}

const message = '你好，世界！';
console.log(message);

// 这是一个示例代码
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((a, b) => a + b, 0);
console.log('Sum:', sum);`;

      document.getElementById('inputCode').value = example;
    }

    // 自动转换（可选）
    document.getElementById('inputCode').addEventListener('input', function () {
      // 可以在这里添加自动转换逻辑
      // 为了性能考虑，建议使用防抖
    });

    // 页面加载完成
    window.addEventListener('load', function () {
      console.log('UTF-16编码转换工具已加载完成');
    });
  </script>
</body>

</html>